import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 键盘工具类
class KeyboardUtils {
  /// 关闭键盘
  static void dismissKeyboard(BuildContext context) {
    FocusScope.of(context).unfocus();
  }

  /// 包装Widget，使其支持点击空白处关闭键盘
  static Widget dismissKeyboardOnTap({required Widget child, bool dismissOnTap = true}) {
    if (!dismissOnTap) return child;

    return GestureDetector(
      onTap: () {
        // 关闭键盘
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      },
      behavior: HitTestBehavior.translucent,
      child: child,
    );
  }

  /// 包装Scaffold，使其支持点击空白处关闭键盘
  static Widget dismissKeyboardScaffold({required Widget child, bool dismissOnTap = true}) {
    if (!dismissOnTap) return child;

    return GestureDetector(
      onTap: () {
        // 关闭键盘
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      },
      behavior: HitTestBehavior.translucent,
      child: child,
    );
  }
}

/// 可关闭键盘的Scaffold
class DismissKeyboardScaffold extends StatelessWidget {
  final Widget child;
  final bool dismissOnTap;
  final PreferredSizeWidget? appBar;
  final Widget? floatingActionButton;
  final Widget? bottomNavigationBar;
  final Widget? drawer;
  final Widget? endDrawer;
  final Color? backgroundColor;
  final bool? resizeToAvoidBottomInset;

  const DismissKeyboardScaffold({
    super.key,
    required this.child,
    this.dismissOnTap = true,
    this.appBar,
    this.floatingActionButton,
    this.bottomNavigationBar,
    this.drawer,
    this.endDrawer,
    this.backgroundColor,
    this.resizeToAvoidBottomInset,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: dismissOnTap
          ? () {
              // 关闭键盘
              FocusScope.of(context).unfocus();
            }
          : null,
      behavior: HitTestBehavior.translucent,
      child: Scaffold(
        appBar: appBar,
        body: child,
        floatingActionButton: floatingActionButton,
        bottomNavigationBar: bottomNavigationBar,
        drawer: drawer,
        endDrawer: endDrawer,
        backgroundColor: backgroundColor,
        resizeToAvoidBottomInset: resizeToAvoidBottomInset,
      ),
    );
  }
}

/// 可关闭键盘的页面包装器
class DismissKeyboardPage extends StatelessWidget {
  final Widget child;
  final bool dismissOnTap;

  const DismissKeyboardPage({super.key, required this.child, this.dismissOnTap = true});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: dismissOnTap
          ? () {
              // 关闭键盘
              FocusScope.of(context).unfocus();
            }
          : null,
      behavior: HitTestBehavior.translucent,
      child: child,
    );
  }
}
